package android.tusnotas.model;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.tusnotas.beans.Instance;

public class InstanceModel {

	
//INSERTS
	public long insertInstance(String description) {
		TusNotasModel.intanceInsertStmt.bindString(1, description);
		return TusNotasModel.intanceInsertStmt.executeInsert();
	}
	
	public long insertInstance(Instance instance) {
		TusNotasModel.intanceInsertStmt.bindString(1, instance.getDescription());
		try{
			return TusNotasModel.intanceInsertStmt.executeInsert();
		}catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}
//END INSERTS
	
	
//DELETES
	public void deleteAllInstances() {
		TusNotasModel.db.delete(TusNotasModel.INSTANCE_TABLE_NAME, null, null);
	}
	
	public void deleteInstanceById(Integer id) {
		TusNotasModel.db.delete(TusNotasModel.INSTANCE_TABLE_NAME, "id = "+id, null);
	}
//END DELETES	
	
	
//SELECTS
	public List<Instance> selectAllInstances() {
		List<Instance> instances = new ArrayList<Instance>();
		Instance instance = null;
		Cursor cursor = TusNotasModel.db.query(TusNotasModel.INSTANCE_TABLE_NAME, new String[] {"id", "description"},
				null, null, null, null, "id ASC");
		
		if (cursor.moveToFirst()) {
			do {
				instance = new Instance();
				instance.setId(cursor.getInt(0));
				instance.setDescription(cursor.getString(1));
				instances.add(instance);
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		return instances;
	}
	
	public Instance selectInstanceByDescription(String description) {
		Instance instance = null;
		Cursor cursor = TusNotasModel.db.query(TusNotasModel.INSTANCE_TABLE_NAME, new String[] {"id", "description"},
				"description ='" + description +"'", null, null, null, "id ASC", "1");
		
		if (cursor.moveToFirst()) {
			do {
				instance = new Instance();
				instance.setId(cursor.getInt(0));
				instance.setDescription(cursor.getString(1));
				
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		return instance;
	}
	
	public Instance selectInstanceById(Integer id) {
		Instance instance = null;
		Cursor cursor = TusNotasModel.db.query(TusNotasModel.INSTANCE_TABLE_NAME, new String[] {"id", "description"},
				"id =" + id , null, null, null, "id ASC", "1");
		
		if (cursor.moveToFirst()) {
			do {
				instance = new Instance();
				instance.setId(cursor.getInt(0));
				instance.setDescription(cursor.getString(1));
				
			} while (cursor.moveToNext());
		}
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		return instance;
	}
	
//END SELECTS	
}